//
//  JsDeviceManager.m
//  JsUtilitySdk
//
//  Created by Gikki Ares on 2023/4/18.
//

#import "JsDeviceManager.h"
#import <UIKit/UIKit.h>
#import <sys/utsname.h>//要导入头文件
#import <JsKeyChainManagerA.h>

NSString * const JsDeviceInfoKeyAppVersion = @"版本";
NSString * const JsDeviceInfoKeyAppBuild = @"Build";
NSString * const JsDeviceInfoKeyFullVersion = @"FullVersion";
NSString * const JsDeviceInfoKeyDeviceName = @"设备名称";
NSString * const JsDeviceInfoKeyDeviceModel = @"设备类型";
NSString * const JsDeviceInfoKeyIosVersion = @"iOS版本";
NSString * const JsDeviceInfoKeyAppName = @"AppName";
NSString * const JsDeviceInfoKeyDeviceId = @"DeviceId";
@implementation JsDeviceManager


static id<JsKeyChainManagerInterface> mKeyChainManager = nil;
+(void)load {
	mKeyChainManager = [JsKeyChainManagerA sharedInstance];
}

+(NSDictionary *)infoDic {
	static NSMutableDictionary * _infoDic;
	if(!_infoDic) {
		_infoDic = [NSMutableDictionary dictionary];
		NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
		NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
		NSString *appBuild = [infoDictionary objectForKey:@"CFBundleVersion"];
		NSString *appFullVersion=[NSString stringWithFormat:@"%@(%@)",appVersion,appBuild];
			// 当前系统版本
		NSString* iOSVersion = [[UIDevice currentDevice] systemVersion];
		NSString * deviceName = [UIDevice currentDevice].name;
		struct utsname systemInfo;
		uname(&systemInfo);
		NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
//		[UIDevice currentDevice].model;
		NSString *appName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
	
		_infoDic[JsDeviceInfoKeyAppName] = appName;
		_infoDic[JsDeviceInfoKeyIosVersion]=iOSVersion;
		_infoDic[JsDeviceInfoKeyAppBuild]=appBuild;
		_infoDic[JsDeviceInfoKeyAppVersion]=appVersion;
		_infoDic[JsDeviceInfoKeyFullVersion]=appFullVersion;
		_infoDic[JsDeviceInfoKeyDeviceName]=deviceName;
		_infoDic[JsDeviceInfoKeyDeviceModel] = deviceModel;
	}
	return _infoDic;
}

/**
 1,获取保存在keychain中的uuid
 2,如果没有就创建一个新的并保存到keychain中.
 */
+ (NSString *)deviceId {
	NSString * deviceId = [mKeyChainManager stringForKey:JsDeviceInfoKeyDeviceId];
	if(!deviceId) {
		deviceId = [self uuidB];
		[mKeyChainManager saveString:deviceId forKey:JsDeviceInfoKeyDeviceId];
	}
	return deviceId;
}

+ (NSString *) uuidB {
	return [[NSUUID UUID] UUIDString];
}
+ (NSString*) uuidA {
	CFUUIDRef newUniqueID = CFUUIDCreate(kCFAllocatorDefault);
	CFStringRef newUniqueIDString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueID);
	NSString *guid = (__bridge NSString *)newUniqueIDString;
	CFRelease(newUniqueIDString);
	CFRelease(newUniqueID);
	return([guid lowercaseString]);
}


@end
